package com.qst.express.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

import com.qst.express.service.OssService;
import com.qst.express.utils.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author:CoolTiger
 * @title: OssServiceImpl
 * @projectName springCloud_edu
 * @description: TODO
 * @date:2022/09/20/11:00:26
 **/
@Service
public class OssServiceImpl implements OssService {
    @Transactional
    @Override
    public String upload(MultipartFile file) {
        //获取阿里云存储相关常量
        String endPoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;


        String uploadUrl = null;
        OSS ossClient = null;
        try {
            ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
            InputStream inputStream = file.getInputStream();
            // 1. 获取文件的名称
            String filename = file.getOriginalFilename();

            //1.1 在文件名称前面加入随机唯一的值
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            filename = uuid + filename;
            //1.2 把文件按照日期进行分类
            String datePath = new DateTime().toString("yyyy/MM/dd");
            filename = datePath + "/" + filename;
            // 2. 创建PutObject请求。
            ossClient.putObject(bucketName, filename, inputStream);
            // 3. 上传阿里云之后路径返回
            uploadUrl = "https://" + bucketName + "." + endPoint + "/" + filename;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return uploadUrl;
    }

}
